<template>
  <div class="search">
    <my-nav-bar
      left-arrow
      left-text="返回"
      @click-left="$router.back()"
      title="千锋商城"
    ></my-nav-bar>
    <van-search
      v-model="searchVal"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
    />
    <!-- 历史记录和列表不能同时存在 -->
    <my-history v-if="!searchList?.length" @tag-search="onSearch($event)"></my-history>
    <ul class="content" v-else>
      <li v-for="(item, index) in searchList" :key="index" @click="goDetail(item)">
        {{ item.goods_name }}
      </li>
    </ul>
  </div>
</template>

<script>
import { qsearch } from "../api/other";
import myHistory from "../components/myHistory.vue";
export default {
  data() {
    return {
      searchVal: "", // 搜索框输入的值
      searchList: [], // 搜索的数据
    };
  },
  created() {},
  methods: {
    goDetail(val) {
      // 跳转商品详情页
      this.$router.push(`/detail/${val.goods_id}`);
    },
    onSearch(val) {
      // 确定搜索触发的函数
      // if (val) {
      //   this.searchVal = val;
      // }

      this.searchVal = val || this.searchVal; // 进阶写法

      qsearch({ query: this.searchVal }).then((res) => {
        // console.log(res);
        this.searchList = res.message;
        if (this.searchVal) {
          // 如果历史记录存在
          this.$store.commit("saveHistory", this.searchVal);
        }
      });
    },
    onCancel() {
      // 点击取消触发的函数
      this.$router.back();
    },
  },
  components: { myHistory },
};
</script>

<style lang="scss">
.search {
  height: 100%;
  .content {
    height: calc(100% - 105px);
    overflow-y: scroll;
    li {
      padding: 10px;
      box-sizing: border-box;
      border-bottom: 1px solid #ccc;
      font-size: 14px;
      line-height: 20px;
    }
  }
}
</style>
